<?php
namespace app\index\model;


use app\index\common\Common;
use app\index\controller\PaypalApi;
use Exception;
use RuntimeException;
use think\Model;

class Waybill extends Model
{
    public static function createWaybill($ids)
    {
        $WaybillClass=new self();
        $OrderClass=new Order();
        $OrderHistoryClass=new OrderHistory();
        $date=date('ymd');
        $temp=date('Y-m-d');
        $rows=$OrderClass->whereIn('id',$ids)->where(function ($query){
            $query->where('logistics_status','<>',1)
            ->whereOr('waybill_id','not null');
        })->select()->toArray();
        if (!empty($rows)){
            return ['status'=>false,'result'=>'有不符合条件的账单'];
        }
        $list=$OrderClass->alias('o')->join('customer c','o.customer_id=c.id')->whereIn('o.id',$ids)->field('o.customer_id,c.nick_name,o.pay_type,c.address,c.phone')->select()->toArray();
        $customer_id=$list[0]['customer_id'];
        foreach ($list as$k=>$v){
            if (!in_array($v['pay_type'],[4,6])){
                return ['status'=>false,'result'=>'未付款的订单不能创建运单'];
            }
            if ($customer_id!==$v['customer_id']){
                return ['status'=>false,'result'=>'不同客户的账单不能创建运单'];
            }
            if(empty($v['address'])){
                return ['status'=>false,'result'=>'先完善客户的地址'];
            }
            if(empty($v['phone'])){
                return ['status'=>false,'result'=>'先完善客户电话'];
            }
        }
        $number_s=$WaybillClass->where('create_time','> time',$temp)->count('id');

        if ($number_s === null) {
            $number_s = 0;
        }
        $id = 'WD' . $date . '0000';
        $order_id = $number_s + 1;
        $max_id_len = strlen($order_id);

        $id_len = strlen($id);
        if ($max_id_len > 4) {
            $max_id_len = 4;
        }
        $ship_no=substr($id,0,$id_len-$max_id_len).($order_id);

        $WaybillClass->startTrans();
        try {
            $Waybill_id = $WaybillClass->insertGetId(['ship_no'=>$ship_no,'customer_name'=>$list[0]['nick_name'],'create_user'=>session('Login_user')['id']]);
            if($Waybill_id){
                $data=['waybill_id'=>$Waybill_id,'logistics_status'=>1];
                $result=$OrderClass->whereIn('id',$ids)->update($data);
                if ($result==false){
                    return ['status'=>false,'result'=>'订单状态修改失败'];
                }
                $data1=[];
                foreach ($ids as $v){
                    $data1[]=['order_id'=>$v,'operator'=>session('Login_user')['id'],'operational'=>'创建运单'];
                }
                $result=$OrderHistoryClass->isUpdate(false)->saveAll($data1);
                if ($result==false){
                    return ['status'=>false,'result'=>'添加订单操作失败'];
                }
            }else{
                throw new RuntimeException('运单创建失败');
            }
            $OrderClass->commit();
            return ['status'=>true,'result'=>['msg'=>'运单创建成功','waybill_id'=>$Waybill_id]];
        }catch (\Exception $e){
            $OrderClass->rollback();
            trace($e->getMessage(),'error');
            return ['status'=>false,'result'=>'添加失败'.$e->getMessage()];
        }

    }

    public static function getWaybillList($search_param,$page_param)
    {
        $WaybillClass=new self();
        $GroupClass=new Group();
        $where=[];
        if ($search_param['ship_no']){
            $where['w.ship_no']=['like','%'.$search_param['ship_no'].'%'];
        }
        if ($search_param['status']){
            if ($search_param['status']==1){
                $where['w.status']=['in',[1,2]];
            }else{
                $where['w.status']=['=',0];
            }
        }
        if ($search_param['customer_name']){
            $where['c.nick_name']=['like','%'.$search_param['customer_name'].'%'];
        }
        if ($search_param['create_group']){
            $where['p.id']=['=',$search_param['create_group']];
        }
        if ($search_param['search_key']&&!empty($search_param['search_value'])){
            $where['w.'.$search_param['search_key']]=['between time',$search_param['search_value']];
        }
        $waybillList=$WaybillClass
            ->alias('w')
            ->join('waybill_image wi','w.id=wi.waybill_id and wi.del_flag=0','left')
            ->join('order o','w.id=o.waybill_id','left')
            ->join('customer c','o.customer_id=c.id')
            ->join('group p','o.create_group=p.id','left')
            ->where($where)->where('w.del_flag',0)
            ->group('w.id')
            ->field('w.id,w.ship_no,w.weight,w.status,w.ship_time,w.logistics_ship_time,w.remark,w.logistics_remark,w.create_time,w.image,group_concat(distinct wi.image order by wi.create_time) image_list,p.group_name,group_concat(distinct o.order_id order by o.create_time separator \',\') order_id,group_concat(o.stock_status) stock_status,group_concat(o.logistics_status) logistics_status,c.nick_name')
            ->order('w.create_time desc')->paginate($page_param['pageSize'],false,['page'=>$page_param['page_num']]);
        $count=$waybillList->total();
        $data=$waybillList->items();
        foreach ($data as $k=>$v){
            if ($v['status']===0){
                $data[$k]['status_name']='待发货';
            }else{
                $data[$k]['status_name']='已发货';
            }
            $data[$k]['order_id']=explode(',',$v['order_id']);

            $data[$k]['image_thumb'] = Common::getThumbImage($v['image']);
            if($v['image_list']){
                $image_list=explode(',',$v['image_list']);
                $data[$k]['image_preview_list']=$image_list;
            }else{
                $data[$k]['image_preview_list']=[];
            }

            $stock_status=explode(',',$v['stock_status']);
            $data[$k]['hasButton']=true;
            foreach ($stock_status as $item){
                if($item!=2){
                    $data[$k]['hasButton']=false;
                }
            }
            $logistics_status=explode(',',$v['logistics_status']);
            foreach ($logistics_status as $item){
                if ($item!=1){
                    $data[$k]['hasButton']=false;
                }
            }
        }
        $group=$GroupClass->where('del_flag',0)->field('group_name,id')->select()->toArray();
        return ['waybillList'=>$data,'total'=>$count,'group'=>$group];
    }

    public static function sendGoods($data)
    {
        $WaybillClass=new self();
        $OrderClass=new Order();
        $waybill_id=[];
        $date=date('Y-m-d H:i:s');
        foreach ($data as $k=>$v){
            if (!$v['weight']){
                return ['status'=>false,'result'=>'重量不能为0'];
            }
            $data[$k]['id']=$v['id'];
            $data[$k]['weight']=$v['weight'];
            $data[$k]['status']=1;
            $data[$k]['ship_time']=$date;
            $waybill_id[]=$v['id'];
//            array_push($id1,$v['id']);
        }
        $order=$OrderClass->whereIn('waybill_id',$waybill_id)->field('id,stock_status,logistics_status')->select()->toArray();
        if (empty($order)){
            return ['status'=>false,'result'=>'订单为空'];
        }
        $ids=[];
        foreach ($order as $v){
            if ($v['stock_status']===1){
                return ['status'=>false,'result'=>'该运单还有订单未出库'];
            }
            if ($v['logistics_status']===2){
                return ['status'=>false,'result'=>'该运单已发货'];
            }
            $ids[]=$v['id'];
        }

        $waybill=$WaybillClass->where('id','in',$waybill_id)->field('id,image')->select()->toArray();
        foreach ($waybill as $key=>$value){
            if(empty($value['image'])) {
                return ['status'=>false,'result'=>'先上传图片'];
            }
        }

        $OrderClass->startTrans();
        try {
            $result=$WaybillClass->isUpdate()->saveAll($data);
            if($result===false){
                return ['status'=>false,'result'=>'发货失败'];
            }
            $result=$OrderClass->whereIn('id',$ids)->update(['logistics_status'=>2]);
            if($result===false){
                return ['status'=>false,'result'=>'修改订单状态失败'];
            }
            $OrderClass->commit();
            return ['status'=>true,'result'=>'发货成功'];
        }catch (\Exception $e){
            $OrderClass->rollback();
            trace($e->getMessage(),'error');
            return ['status'=>false,'result'=>'创建运单失败'.$e->getMessage()];
        }
    }

    public static function getLogisticsWaybillList($search_param,$page_param)
    {
        $WaybillClass=new self();
        $where=[];
        if ($search_param['ship_no']){
            $where['w.ship_no']=['like','%'.$search_param['ship_no'].'%'];
        }
        if ($search_param['logistics_waybill']){
            $where['w.logistics_waybill']=['like','%'.$search_param['logistics_waybill'].'%'];
        }
        if (is_numeric($search_param['logistics_id'])){
            $where['w.logistics_id']=['=',$search_param['logistics_id']];
        }
        if ($search_param['customer_name']){
            $where['c.nick_name']=['like','%'.$search_param['customer_name'].'%'];
        }
        if (is_numeric($search_param['status'])){
            if ($search_param['status']===2){
                $where['status']=['=',2];
            }else{
                $where['status']=['=',1];
            }
        }
        if ($search_param['search_key']&&!empty($search_param['search_value'])){
            $where[$search_param['search_key']]=['between time',$search_param['search_value']];
        }
        $where['w.del_flag']=['=',0];
        $where['w.status']=['>',0];
        $list=$WaybillClass->alias('w')
            ->join('logistics l','w.logistics_id=l.id','left')
            ->join('order o','w.id=o.waybill_id','left')
            ->join('customer c','o.customer_id=c.id','left')
            ->join('country co','c.country=co.id','left')
            ->where($where)
            ->group('w.id')
            ->order('w.ship_time desc')
            ->field('w.*,l.company,l.type,c.address,c.nick_name,c.zip_code,c.id customer_id,c.phone,co.country_name')
            ->paginate($page_param['pageSize'],false,['page'=>$page_param['page_num']]);
        $count=$list->total();
        $data=$list->items();
        foreach ($data as $k=>$v){
            $data[$k]['company']=$v['logistics_name']?$v['logistics_name']:$v['company'];
            if ($v['real_weight']==0){
                $data[$k]['real_weight']='';
            }
            if ($v['status']==1){
                $data[$k]['status_text']='待发货';
            }else{
                $data[$k]['status_text']='已发货';
            }
        }
        return ['list'=>$data,'total'=>$count];
    }

    public static function logisticsWaybillEdit($data)
    {
        $WaybillClass=new self();
        $waybillHistoryClass=new WaybillHistory();
        $orderClass=new Order();
        $WaybillClass->startTrans();
        $logistics_id=$data['logistics_id'];
        $logistics=Logistics::where('id',$logistics_id)->where('del_flag',0)->find();
        if ($logistics['type']==1){
            if (!$data['logistics_name']){
                return ['status'=>false,'result'=>'请填写物流商名称'];
            }
        }
        try {
            $waybill_data=$WaybillClass->alias('w')
                ->where(['w.id'=>$data['id'],'w.del_flag'=>0])
                ->field('w.id,w.customer_name,w.ship_no,w.logistics_waybill,w.logistics_id,logistics_name')
                ->find();
            if(empty($waybill_data)){
                return ['status'=>false,'result'=>'运单未找到'];
            }
            $order_data = $orderClass->alias('o')
                ->join('order_payment op', 'o.id=op.order_id and op.del_flag=0 and op.payment_type=1', 'left')
                ->where('o.waybill_id', $data['id'])
                ->where(['o.del_flag' => 0])
                ->field('op.invoice_payment_id,o.create_group,o.create_user')
                ->select();
            $group = $order_data[0]['create_group'];
            $user = $order_data[0]['create_user'];

            $waybill_update=[
                'id'=>$data['id'],
                'status'=>2,
                'logistics_ship_time'=>date('Y-m-d H:i:s'),
                'real_weight'=>$data['real_weight'],
                'logistics_waybill'=>$data['logistics_waybill'],
                'logistics_id'=>$data['logistics_id'],
                'logistics_name'=>$data['logistics_name'],
            ];
            $result=$WaybillClass->isUpdate(true)->save($waybill_update);
            if ($result===false){
                return ['status'=>false,'result'=>'编辑失败'];
            }
            $history_data=[
                'real_weight'=>$data['real_weight'],
                'weight'=>$data['weight'],
                'logistics_waybill'=>$data['logistics_waybill'],
                'customer_name'=>$data['customer_name'],
                'logistics_id'=>$data['logistics_id'],
                'waybill_id'=>$data['id'],
                'create_user'=>session('Login_user')['id'],
            ];
            $result=$waybillHistoryClass->insert($history_data);
            if ($result===false){
                return ['status'=>false,'result'=>'历史记录添加失败'];
            }

            $status = true;
            $res='';
            $tracker=[];
            $ship=0;
            if (!$waybill_data['logistics_waybill'] && !$waybill_data['logistics_id']) {
                $ship=1;
                foreach ($order_data as $k => $v) {
                    if (!$v['invoice_payment_id']) {
                        continue;
                    }
                    $tracker[$k]['transaction_id'] = $v['invoice_payment_id'];
                    $tracker[$k]['tracking_number'] = $data['logistics_waybill'];
                    $tracker[$k]['status'] = 'SHIPPED';
                    if ($logistics['type'] == 1) {
                        $tracker[$k]['carrier'] = 'OTHER';
                        $tracker[$k]['carrier_name_other'] = $data['logistics_name'];
                    } else {
                        $tracker[$k]['carrier'] = $logistics['company'];
                    }
                }
                //新增
                if (!empty($tracker)) {
                    ['status' => $status, 'result' => $res] = PaypalApi::addWaybillCode($tracker, $group);
                }
            } else {
                if($waybill_data['logistics_id']===$data['logistics_id'] && $waybill_data['logistics_name']==$data['logistics_name'] && $waybill_data['logistics_waybill']===$data['logistics_waybill']){

                }else {
                    $ship=2;
                    $pre_tracking_number = $waybill_data['logistics_waybill'];
                    foreach ($order_data as $k => $v) {
                        $tracker['transaction_id'] = $v['invoice_payment_id'];
                        $tracker['tracking_number'] = $data['logistics_waybill'];
                        $tracker['status'] = 'SHIPPED';
                        if ($logistics['type'] == 1) {
                            $tracker['carrier'] = 'OTHER';
                            $tracker['carrier_name_other'] = $data['logistics_name'];
                        } else {
                            $tracker['carrier'] = $logistics['company'];
                        }
                        if ($v['invoice_payment_id']) {
                            //更新
                            ['status' => $status, 'result' => $res] = PaypalApi::updateWaybillCode($tracker, $group, $pre_tracking_number);
                        }
                    }
                }
            }
            if ($status === false) {
                trace('invoice update error '.$res.' '.json_encode($tracker,true),'error');
            }
            if($ship){
                try {
                    $NewsClass=new News();
                    $content=$ship===1?'物流商已发货':'物流商信息已更新';
                    $NewsClass->isUpdate(false)->save(['type'=>2,'waybill_id'=>$data['id'],'content'=>$content,'group'=>$group]);
                    Common::paymentNotice($user, $group, [
                        'type' => 'push',
                        'key' => 'home_waybill_list',
                        'msg' => $content,
                        'data' => [
                            'content'=>$content,
                            'customer_name' => $waybill_data['customer_name'],
                            'waybill' => $waybill_data['ship_no'],
                            'logistics_company' => $logistics['type']===0?$logistics['company']:$data['logistics_name'],
                            'logistics_waybill' => $data['logistics_waybill'],
                            'is_new' => true,
                        ]],'order');
                }catch (Exception $e){
                    trace('ipn payment notice error'.$e->getMessage(),'error');
                }
            }
            $WaybillClass->commit();
            return ['status'=>true,'result'=>'编辑成功'];
        }catch (Exception $e) {
            $WaybillClass->rollback();
            trace($e->getMessage(),'error');
            return ['status'=>false,'result'=>'保存失败'.$e->getMessage()];
        }

    }
    /*没用*/
    public static function logisticsWaybillSend($id)
    {
        $WaybillClass=new self();
        $date=date('Y-m-d H:i:s',time());
        $waybillHistoryClass=new WaybillHistory();
        $WaybillClass->startTrans();
        try {
            $result=$WaybillClass->where('id',$id)->update(['status'=>2,'logistics_ship_time'=>$date]);
            if (!$result){
                return ['status'=>false,'result'=>'发货失败'];
            }
            $data=$WaybillClass->where('id',$id)->field('id waybill_id,weight,real_weight,logistics_waybill,customer_name,logistics_id')->find()->oArray();
            $data['create_user']=session('Login_user')['id'];
            $data['action']=1;
            $row=$waybillHistoryClass->insert($data);
            if (!$row){
                return ['status'=>false,'result'=>'备份失败'];
            }
            $WaybillClass->commit();
            return ['status'=>true,'result'=>'发货成功'];
        }catch (Exception $e) {
            $WaybillClass->rollback();
            trace($e->getMessage(),'error');
            return ['status'=>false,'result'=>'保存失败'.$e->getMessage()];
        }
    }

    public static function addRemark($id,$data)
    {
        $WaybillClass=new self();
        $result=$WaybillClass->isUpdate(true)->save($data,['id'=>$id]);
        if (!$result){
            return ['status'=>false,'result'=>'编辑失败'];
        }
        return ['status'=>true,'result'=>'编辑成功'];
    }

    public static function mergeWaybill($data,$id,$ids)
    {
        $WaybillClass=new self();
        $OrderClass=new Order();
        $WaybillImageClass=new WaybillImage();
        $list=$OrderClass->where('waybill_id','in',$id)->where('del_flag',0)->select()->toArray();
        $bool=true;
        $isSend=true;
        $isUnique=true;
        foreach ($list as $k=>$v){
            if ($list[0]['stock_status']!==$v['stock_status']){
                $bool=false;
            }
            if ($v['logistics_status']===2){
                $isSend=false;
            }
            if ($list[0]['customer_id']!==$v['customer_id']){
                $isUnique=false;
            }
        }
        if (!$bool){
            return ['status'=>false,'result'=>'账单状态不一致'];
        }
        if (!$isUnique){
            return ['status'=>false,'result'=>'不能合并不同客户的运单'];
        }
        if (!$isSend){
            return ['status'=>false,'result'=>'不能合并已发货的运单'];
        }
        $waybill_id=$data[0];
        $WaybillClass->startTrans();
        try {
            $result=$OrderClass
                ->where('waybill_id','in',$id)->where('del_flag',0)
                ->update(['waybill_id'=>$waybill_id]);
            if ($result===false){
                return ['status'=>false,'result'=>'运单合并失败'];
            }
            $result=$WaybillClass->where('id','in',$ids)->update(['del_flag'=>1]);
            if ($result===false){
                return ['status'=>false,'result'=>'运单合并失败'];
            }
            $result=$WaybillImageClass->where('waybill_id','in',$ids)->update(['waybill_id'=>$waybill_id]);
            if($result===false){
                return ['status'=>false,'result'=>'图片合并失败'];
            }
            $WaybillClass->commit();
            return ['status'=>true,'result'=>'运单合并成功'];
        }catch (Exception $e) {
            $WaybillClass->rollback();
            trace($e->getMessage(),'error');
            return ['status'=>false,'result'=>'运单合并失败'.$e->getMessage()];
        }
    }

    public static function getLogisticsById($id)
    {
        $WaybillClass=new self();
        $OrderClass=new Order();
        $where=[];
        $where['w.id']=['=',$id];
        $list=$WaybillClass->alias('w')
            ->join('logistics l','w.logistics_id=l.id','left')
            ->where($where)
            ->order('w.ship_time desc')
            ->field('w.*,l.company,l.type')
            ->find();
        $customer=$OrderClass->alias('o')
            ->join('customer c','o.customer_id=c.id','left')
            ->join('country co','c.country=co.id','left')
            ->where('waybill_id',$id)
            ->field('c.address,c.customer_name,c.city,c.zip_code,c.id,c.phone,co.country_name')
            ->find();
        $list['customer_id']=$customer['id'];
        $list['country']=$customer['country_name'];
        $list['city']=$customer['city'];
        $list['address']=$customer['address'];
        $list['customer_name']=$customer['customer_name'];
        $list['postcode']=$customer['zip_code'];
        $list['phone']=$customer['phone'];
        if ($list['type']==1){
            $list['company']=$list['logistics_name'];
            $list['l_show']=true;
        }else{
            $list['l_show']=false;
        }
        if ($list['real_weight']==0){
            $list['real_weight']=$list['weight'];
        }
        if ($list['status']==1){
            $list['status_text']='待发货';
        }else{
            $list['status_text']='已发货';
        }
        return $list;
    }

    public static function changeImage($data){
        $WaybillImageClass=new WaybillImage();
        $WaybillClass=new self();
        $image_data=$WaybillImageClass->where('waybill_id',$data['id'])->where('del_flag','=',0)->field('id,waybill_id,image')->select()->toArray();
        $insert_image=[];
        $update_image=[];
        $user=session('Login_user');
        foreach ($data['image'] as $key=>$value){
            if(isset($image_data[$key])) {
                $update_image[] = ['id'=>$image_data[$key]['id'],'image'=>$value['image'],'del_flag'=>0];
            }else{
                $insert_image[]=['image'=>$value['image'],'waybill_id'=>$data['id'],'create_user'=>$user['id']];
            }
        }

        $WaybillClass->startTrans();
        try {
            $result=$WaybillClass->where('id','=',$data['id'])->update(['image'=>$data['image'][0]['image']]);
            if($result===false){
                return ['status'=>false,'msg'=>'添加运单图片失败'];
            }

            $result = $WaybillImageClass->where('waybill_id', '=', $data['id'])->update(['del_flag' => 1]);
            if ($result === false) {
                return ['status' => false, 'result' => '更新图片失败'];
            }
            if (!empty($insert_image)) {
                $result = $WaybillImageClass->isUpdate(false)->saveAll($insert_image);
                if ($result === false) {
                    return ['status' => false, 'result' => '添加失败'];
                }
            }
            if (!empty($update_image)) {
                $result = $WaybillImageClass->isUpdate(true)->saveAll($update_image);
                if ($result === false) {
                    return ['status' => false, 'result' => '更新成功'];
                }
            }
            $WaybillClass->commit();
            return ['status' => true, 'result' => '更新成功'];
        }catch (Exception $e){
            $WaybillClass->rollback();
            trace('changeImage '.$e->getMessage(),'error');
            return ['status'=>false,'result'=>'更新失败'];
        }
    }

    public static function getWaybillDataForPdfByIds($ids){
        $WaybillClass=new self();

        $where['w.id']=['in',$ids];
        $where['o.del_flag']=['=',0];
        $where['c.del_flag']=['=',0];
        $waybill_data=$WaybillClass->alias('w')
            ->join('order o','w.id=o.waybill_id and o.del_flag=0','left')
            ->join('customer c','o.customer_id=c.id ','left')
            ->join('group g','o.create_group=g.id','left')
            ->field('c.nick_name,w.ship_no,o.create_group,g.logo_image,g.waybill_note,g.logo_width_pdf width,g.logo_height_pdf height')
            ->where($where)
            ->group('w.id')
            ->select()->toArray();
        return $waybill_data;
    }
}
